package cn.kevinking.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * define config for spring security
 * @author kevinking
 * @since 13 Apr 2025
 */
@EnableWebSecurity
@Configuration
public class SecurityConfig {

	/**
	 * config default password encoder in bcrypt
	 * @return bcrypt password encoder
	 */
	@Bean
	public PasswordEncoder defaultPasswordEncoder() {
		return new BCryptPasswordEncoder();
	}

	/**
	 * global expose authentication manager object
	 * @return authentication manager
	 */
	@Bean
	public AuthenticationManager getAuthenticationManager(AuthenticationConfiguration configuration) throws Exception {
		return configuration.getAuthenticationManager();
	}

	/**
	 * override http config
	 * @param http http security config object
	 * @return security filter chain
	 * @throws Exception any exception
	 */
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		return http.csrf(AbstractHttpConfigurer::disable)
				.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
				.authorizeHttpRequests(
						request -> request
						// permit config
						.requestMatchers("/auth/login").anonymous()
						// rest of all to authenticate
						.anyRequest().authenticated()
				)
				.build();
	}
}
